package com.lagou.edu.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lagou.edu.pojo.ApiResponse;
import com.lagou.edu.pojo.LoginParams;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.lagou.edu.interceptor.LoginConstants.USER_KEY;

/**
 * @author leonzhangxf
 */
public class LoginCheckInterceptor implements HandlerInterceptor {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
        LoginParams params = (LoginParams) request.getSession().getAttribute(USER_KEY);
        if (null == params) {
            request.getSession().setAttribute(USER_KEY, null);
            String ajaxRequest = request.getHeader("X-Requested-With");
            if ("XMLHttpRequest".equals(ajaxRequest)) {
                String resStr = objectMapper.writeValueAsString(
                    ApiResponse.newErr(401, "UnAuthorized")
                );
                response.getWriter().write(resStr);
            } else {
                response.sendRedirect("/login/login-page");
            }

            return false;
        }
        return true;
    }
}
